import { Order } from './models/Order';
import { MapPoint } from './models/City';
import inside from 'point-in-polygon';
import { OrderState } from '../objects/internal/OrderState';
import { OrderFilterCondition } from '../objects/internal/OrderFilterCondition';
import Gopher from '../tooling/Gopher';

export function filterTimeSpan(left: Date, right: Date, x: Order): boolean {
	const orderTime = (new Date(x.startTime)).getTime();
	const leftTime = left.getTime();
	const rightTime = right.getTime();
	return leftTime <= orderTime && orderTime <= rightTime;
}

export function filterPosition(contour: MapPoint[], x: MapPoint): boolean {
	const point = [x.lng, x.lat];
	const polygon = contour.map(x => [x.lng, x.lat]);
	return inside(point, polygon);
}

export async function applyOrderFilter(gopher: Gopher, filter: OrderFilterCondition): Promise<Order[]> {
	console.log(filter);

	const selector = {};

	if (filter.orderState !== OrderState.ANY) {
		Reflect.set(selector, 'state', filter.orderState);
	}

	const orders = await gopher.queryOrders(selector);
	let firstPass;
	if (filter.city !== '全部' && filter.city.length > 0) {
		const city = await gopher.getCity(filter.city);
		if (!city) {
			firstPass = orders;
		} else {
			firstPass = orders.filter(x => filterPosition(city.region, x.startPosition));
		}
	} else {
		firstPass = orders;
	}

	return firstPass.filter(x => filterTimeSpan(filter.fromTime, filter.toTime, x));
}
